﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YwhLib;

namespace YwhCore
{
    /// <summary>
    /// 配置信息
    /// </summary>
    public class ConfigService
    {
        /// <summary>
        /// 数据库
        /// </summary>
        public static IFreeSql Fsql { get; set; }

        /// <summary>
        /// 建筑缓存
        /// </summary>
        public static List<Building> Buildings { get; set; }

        /// <summary>
        /// 期数缓存
        /// </summary>
        public static List<Phase> Phases { get; set; }

        /// <summary>
        /// 单元缓存
        /// </summary>
        public static List<Unit> Units { get; set; }

        /// <summary>
        /// 房屋缓存
        /// </summary>
        public static List<Room> Rooms { get; set; }

        /// <summary>
        ///  加载数据库和缓存
        /// </summary>
        /// <param name="conf"></param>
        public static void LoadDbAndCache(Microsoft.Extensions.Configuration.IConfiguration conf)
        {
            FreeSql.FreeSqlBuilder builder = new FreeSql.FreeSqlBuilder();

            string dbconn = conf.GetSection("DbConn").Value;
            builder.UseConnectionString(FreeSql.DataType.MySql, dbconn);
            Console.WriteLine("find mysql config");

            IFreeSql fsql = builder.UseAutoSyncStructure(true).Build();

            if (!fsql.Ado.ExecuteConnectTest())
            {
                string erradd = "";
                if (fsql.Ado.MasterPool.UnavailableException != null) erradd = "\r\n" + fsql.Ado.MasterPool.UnavailableException.Message + "\r\n" + fsql.Ado.MasterPool.UnavailableException.StackTrace;
                System.Console.WriteLine("database connect error：" + dbconn + erradd);
                System.Environment.Exit(500);
            }

            Buildings = fsql.Select<Building>().ToList();
            Units = fsql.Select<Unit>().ToList();
            Rooms = fsql.Select<Room>().ToList();
            Phases = fsql.Select<Phase>().ToList();
            fsql.Select<Meeting>().First();
            fsql.Select<Inhabitant>().First();

            fsql.Dispose();
            fsql = builder.UseAutoSyncStructure(false).Build();
            YwhCore.ConfigService.Fsql = fsql;
        }

    }
}